<template>
  <header class="header">
    <div class="container">
      <!-- 顶部信息栏 -->
      <div class="top-bar">
        <div class="left">
          
          <span>欢迎来到电商平台</span>
          <template v-if="!isLoggedIn">
            <router-link to="/login">登录</router-link>
            <!-- 显示注册页面 -->
            <a @click="showRegister">注册</a>
          </template>
          <template v-else>
            <span>欢迎，{{ userInfo.username }}</span>
            <a @click="handleLogout">退出登录</a>
          </template>
        </div>
        <div class="right">
          <!-- 入驻商城或管理商铺(仅登录用户可见) -->
          <template v-if="isLoggedIn">
            <router-link v-if="!isShopOwner" to="/user/apply-shop">入驻商城</router-link>
            <a v-else @click="goToMerchant" class="nav-link">管理商铺</a>
          </template>
          <router-link to="/user">个人中心</router-link>
          <router-link to="/user" @click="goToUserOrders">我的订单</router-link>
          <router-link to="/user/favorites">我的收藏</router-link>
          <router-link to="/user/service">平台客服</router-link>
        </div>
      </div>

      <!-- 主导航栏 -->
      <div class="main-nav">
        <img class="logo-img" src="@/assets/jiang.jpg" alt="Logo" />
        <div class="logo">
          <router-link to="/">
            <h1>匠心电商首页</h1>
          </router-link>
        </div>
        <div class="search">
          <input 
            type="text" 
            v-model="searchKeyword" 
            placeholder="请输入搜索关键词"
            @keyup.enter="handleSearch"
          >
          <button @click="handleSearch">搜索</button>
        </div>
        <div class="cart">
          <router-link to="/cart" class="cart-link">
            <i class="cart-icon">🛒</i>
            <span>购物车</span>
            <span v-if="cartCount > 0" class="cart-count">{{ cartCount }}</span>
          </router-link>
        </div>
      </div>
    </div>
  </header>
</template>

<script setup>
import { ref, reactive, onMounted, computed, watch } from 'vue'
import { useRouter } from 'vue-router'
import { logout } from '@/api/user'
import { isShop } from '@/api/shop'
import { useSearchStore } from '@/stores/search'
import { useUserStore } from '@/stores/modules/user'
import { ElMessage } from 'element-plus'

const router = useRouter()
const searchStore = useSearchStore()
const userStore = useUserStore()
const searchKeyword = computed({
  get: () => searchStore.keyword,
  set: (val) => searchStore.setKeyword(val)
})

// 使用计算属性从 store 获取登录状态和用户信息
const isLoggedIn = computed(() => !!userStore.accessToken)
const userInfo = computed(() => ({
  username: userStore.userInfo?.nickName || userStore.userInfo?.phone || '',
  phone: userStore.userInfo?.phone || '',
  nickName: userStore.userInfo?.nickName || ''
}))

const cartCount = ref(0)
const isRegisterVisible = ref(false)
const isShopOwner = ref(false)

// 显示注册页面
const showRegister = () => {
  isRegisterVisible.value = !isRegisterVisible.value
}

// 退出登录
const handleLogout = async () => {
  try {
    await logout()  // 调用登出接口
    // 清除用户状态
    userStore.logout()
    // 重置商铺状态
    isShopOwner.value = false
    // 跳转到首页
    router.push('/')
  } catch (error) {
    console.error('登出失败:', error)
  }
}

// 检查用户是否已入驻商城
const checkShopStatus = async () => {
  if (!isLoggedIn.value) {
    isShopOwner.value = false
    return
  }
  
  try {
    console.log('检查商家状态...')
    const result = await isShop()
    console.log('isShop API返回结果:', result)
    isShopOwner.value = !!result // 将API返回结果转换为布尔值
    
    // 更新userStore中的商家身份
    if (userStore.userInfo && isShopOwner.value !== userStore.userInfo.isMerchant) {
      console.log('更新用户商家身份:', isShopOwner.value)
      userStore.updateUserMerchantStatus(isShopOwner.value)
    }
    
    console.log('商铺入驻状态:', isShopOwner.value)
  } catch (error) {
    console.error('获取商铺状态失败:', error)
    isShopOwner.value = false
  }
}

// 组件挂载时检查登录状态和商铺状态
onMounted(async () => {
  await userStore.checkAndRefreshToken()
  // 如果用户已登录，检查商铺状态
  if (isLoggedIn.value) {
    await checkShopStatus()
  }
})

// 监听登录状态变化，更新商铺状态
watch(isLoggedIn, async (newValue) => {
  if (newValue) {
    await checkShopStatus()
  } else {
    isShopOwner.value = false
  }
})

// 模拟分类数据
const categories = ref([
  { id: 0, name: '手机数码' },
  { id: 1, name: '电脑办公' },
  { id: 2, name: '家用电器' },
  { id: 3, name: '服装鞋包' },
  { id: 4, name: '食品生鲜' }
])

// 跳转到分类页面
const goToCategory = (categoryId) => {
  router.push(`/category/${categoryId}`)
}

// 搜索处理
const handleSearch = () => {
  if (searchKeyword.value.trim()) {
    router.push({
      path: '/search',
      query: { keyword: searchKeyword.value.trim() }
    })
  }
}

// 跳转到用户订单页面
const goToUserOrders = () => {
  router.push({ name: 'UserOrders' })
}

// 跳转到商家后台
const goToMerchant = () => {
  console.log('点击管理商铺按钮，商家状态:', isShopOwner.value)
  if (!isShopOwner.value) {
    ElMessage.warning('您还不是商家，请先申请入驻')
    return
  }
  console.log('准备跳转到商家后台...')
  // 使用完整路径，避免相对路径问题
  window.location.href = '/merchant/dashboard'
}
</script>

<style scoped>
.header {
  background: #fff;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
  border-radius: 0 0 8px 8px;
  width: 100%;
  margin: 0;
}

.container {
  width: 1200px;
  margin: 0 auto;
  padding: 0 20px;
  box-sizing: border-box;
}

.top-bar, .main-nav {
  border-radius: 8px;
}

/* 顶部信息栏样式 */
.top-bar {
  height: 36px;
  line-height: 36px;
  background-color: #f5f5f5;
  display: flex;
  justify-content: space-between;
  padding: 0 15px;
  font-size: 12px;
}

.top-bar a {
  color: var(--text-regular);
  margin: 0 10px;
  text-decoration: none;
}

.top-bar a:hover {
  color: var(--primary-color);
}

/* 主导航栏样式 */
.main-nav {
  height: 100px;
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 0 15px;
}

.logo h1 {
  margin: 0;
  font-size: 24px;
  color: #ff4d4f;
  font-weight: bold;
  letter-spacing: 2px;
}

.logo-img {
  width: 50px;
  height: 50px;
}

.search {
  display: flex;
  width: 500px;
}

.search input {
  flex: 1;
  padding: 10px;
  border: 2px solid #ff4d4f;
  border-right: none;
  border-radius: 4px 0 0 4px;
  outline: none;
}

.search input:focus {
  border-color: #ff7875;
}

.search button {
  padding: 0 30px;
  background-color: #ff4d4f;
  color: white;
  border: none;
  border-radius: 0 4px 4px 0;
  cursor: pointer;
  font-weight: bold;
  transition: background 0.2s;
}

.search button:hover {
  background-color: #ff7875;
}

.cart-link {
  display: flex;
  align-items: center;
  padding: 8px 15px;
  border: 1px solid var(--border-color);
  border-radius: 4px;
  text-decoration: none;
  color: var(--text-regular);
}

.cart-count {
  background-color: var(--danger-color);
  color: white;
  padding: 2px 6px;
  border-radius: 10px;
  font-size: 12px;
  margin-left: 5px;
}

/* 分类导航样式 */
.category-nav {
  height: 40px;
  background-color: var(--primary-color);
}

.category-list {
  display: flex;
  list-style: none;
  margin: 0;
  padding: 0;
  height: 100%;
}

.category-list li {
  padding: 0 20px;
  color: white;
  line-height: 40px;
  cursor: pointer;
  transition: background-color 0.3s;
}

.category-list li:hover {
  background-color: rgba(255, 255, 255, 0.1);
}
</style>